<?php


namespace App\Polling\Repositories;


use App\Models\Competition;
use App\Models\Group;
use App\Models\Introduction;
use App\Models\Leaguetable;
use App\Models\Matchs;
use App\Models\Player;
use App\Models\Suspension;
use Carbon\Carbon;

// Added Suspension model
use App\Models\Team;

class IndexRepository extends BaseRepository {
    /**
     * Corresponding method for IndexService::index()
     */
    public function index() {
        $userKey = env('userKey');
        $query = Matchs::where('competitionId', 15)->Where(function ($query) {
            $query->where(function ($query) {
                $query->where('homeTeamId', 300)->where('awayTeamId', 341);
            })->orWhere(function ($query) {
                $query->where('homeTeamId', 341)->where('awayTeamId', 300);
            });
        })->toSql();
        //$sql = str_replace_array('?', $query->getBindings(), $query->toSql());
        print_r($query);
        return null;
    }

    /**
     * 查询赛事基本信息
     * 接口URL: http://data43.aistat.cn/competitions/infos
     * 请求类型: get
     * 请求参数: key (必填, String)
     */
    public function getCompetitionsInfos($data) {
        $userKey = env('userKey');
        foreach ($data as $value) {
            $competition = Competition::find($value['id']);
            if (empty($competition)) {
                Competition::create([
                    'id' => $value['id'],
                    'name' => $value['name'],
                    'nameFull' => $value['nameFull'],
                    'nameEn' => $value['nameEn'],
                    'nameEnFull' => $value['nameEnFull'],
                    'competitionType' => $value['competitionType'],
                    'teamType' => $value['teamType'],
                    'gender' => $value['gender'],
                    'country' => $value['country'],
                    'country_id' => $value['countryId'],
                    'currSeason' => $value['currSeason'],
                    'seasons' => implode('|', $value['seasons']),
                    'teamsNum' => $value['teamsNum'],
                    'playersNum' => $value['playersNum'],
                    'averageAge' => $value['averageAge'],
                    'marketValue' => $value['marketValue'],
                    'playerMv' => $value['playerMv'],
                    'teamMv' => $value['teamMv'],
                    'colour' => $value['colour'],
                    'hasDetail' => $value['hasDetail']
                ]);
            } else {
                $competition->name = $value['name'];
                $competition->nameFull = $value['nameFull'];
                $competition->nameEn = $value['nameEn'];
                $competition->nameEnFull = $value['nameEnFull'];
                $competition->competitionType = $value['competitionType'];
                $competition->teamType = $value['teamType'];
                $competition->gender = $value['gender'];
                $competition->country = $value['country'];
                $competition->country_id = $value['countryId'];
                $competition->currSeason = $value['currSeason'];
                $competition->seasons = implode('|', $value['seasons']);
                $competition->teamsNum = $value['teamsNum'];
                $competition->playersNum = $value['playersNum'];
                $competition->averageAge = $value['averageAge'];
                $competition->marketValue = $value['marketValue'];
                $competition->playerMv = $value['playerMv'];
                $competition->teamMv = $value['teamMv'];
                $competition->colour = $value['colour'];
                $competition->save();
            }
        }
        return true;
    }

    /**
     * 查询赛事规则和介绍
     * 接口URL: http://data43.aistat.cn/competitions/introductions
     * 请求类型: get
     * 请求参数: key (必填, String)
     */
    public function getCompetitionsIntroductions($data) {
        $userKey = env('userKey');
        foreach ($data as $value) {
            Introduction::updateOrCreate(['competitionId' => $value['competitionId']], $value);
        }
        return true;
    }

    /**
     * 查询赛事分组
     * 接口URL: http://data43.aistat.cn/competitions/groups
     * 请求类型: get
     * 请求参数: key (必填, String), competitionId (可选, Int), season (可选, String)
     */
    public function getCompetitionsGroups($data) {
        $userKey = env('userKey');
        foreach ($data as $value) {
            Group::updateOrCreate(['id' => $value['id']], $value);
        }
        return true;
    }

    /**
     * 查询球队基本信息
     * 接口URL: http://data43.aistat.cn/teams/infos
     * 请求类型: get
     * 请求参数: Key (必填, String), competitionId (可选, Int), season (可选, String)
     */
    public function getTeamsInfos($data) {
        $userKey = env('userKey');
        foreach ($data as $value) {
            Team::updateOrCreate(['id' => $value['id']], $value);
        }
        return null;
    }

    /**
     * 查询赛事积分榜
     * 接口URL: http://data43.aistat.cn/competitions/leagueTables
     * 请求类型: get
     * 请求参数: key (必填, String), competitionId (必填, Int), season (可选, String)
     */
    public function getCompetitionsLeagueTables() {
        $userKey = env('userKey');
        $competitionList = Competition::where('id', '<=', 30)->get();
        foreach ($competitionList as $value) {
            $ret = curlGetJson('http://data43.aistat.cn/competitions/leagueTables?key=' . $userKey . '&competitionId=' . $value['id']);
            if ($ret['state'] == 'success') {
                foreach ($ret['leagueTables'] as $val) {
                    Leaguetable::updateOrCreate(['id' => $val['id']], $val);
                }
            } else {
                throwBusinessException($ret['errorMsg']);
            }
        }
        return null;
    }

    /**
     * 查询球员基本信息
     * 接口URL: http://data43.aistat.cn/players/infos
     * 请求类型: get
     * 请求参数: key (必填, String), competitionId (可选, Int), teamId (可选, Int), playerIds (可选, String), day (可选, Int)
     */
    public function getPlayersInfos() {
        $userKey = env('userKey');
        $competitionList = Competition::where('id', '<', 30)->get();
        foreach ($competitionList as $value) {
            $ret = curlGetJson('http://data43.aistat.cn/players/infos?key=' . $userKey . '&competitionId=' . $value['id']);
            if ($ret['state'] == 'success') {
                foreach ($ret['players'] as $val) {
                    Player::updateOrCreate(['id' => $val['id']], $val);
                }
            } else {
                throwBusinessException($ret['errorMsg']);
            }
        }
        return null;
    }


    /**
     * 查询球员伤停信息
     * 接口URL: http://data43.aistat.cn/players/suspensions
     * 请求类型: get
     * 请求参数: key (必填, String), competitionId (可选, Int), teamId (可选, Int)
     */
    public function getPlayersSuspensions() {
        $userKey = env('userKey');
        $competitionList = Competition::where('id', '<', 30)->get();
        foreach ($competitionList as $val) {
            $ret = curlGetJson('http://data43.aistat.cn/players/suspensions?key=' . $userKey . '&competitionId=' . $val['id']);
            if ($ret['state'] == 'success') {
                foreach ($ret['suspensions'] as $value) {
                    Suspension::updateOrCreate(['playerId' => $value['playerId']], $value);
                }

            }
        }
        return true;
    }


    /**
     * 查询转会信息
     * 接口URL: http://data43.aistat.cn/transfers/queryByDate
     * 请求类型: get
     * 请求参数: key (必填, String), beginDate (必填, String), endDate (必填, String)
     */
    public function getTransfersByDate() {
        $userKey = env('userKey');
        $start_time = date('Ymd', strtotime('-7 days'));
        $end_time = date('Ymd');
        $ret = curlGetJson('http://data43.aistat.cn/transfers/queryByDate?key=' . $userKey . '&beginDate=' . $start_time . '&endDate=' . $end_time);
        if ($ret['state'] == 'success') {
            foreach ($ret['transfers'] as $value) {
                \App\Models\Transfers::updateOrCreate(['id' => $value['id']], $value);
            }
        }
        return null;
    }

    /**
     * 查询国家信息
     * 接口URL: http://data43.aistat.cn/countries/infos
     * 请求类型: get
     * 请求参数: key (必填, String)
     */
    public function getCountriesInfos() {
        $userKey = env('userKey');
        $ret = curlGetJson('http://data43.aistat.cn/countries/infos?key=' . $userKey);
        if ($ret['state'] == 'success') {
            foreach ($ret['countries'] as $value) {
                \App\Models\Countrie::updateOrCreate(['id' => $value['id']], $value);
            }
        } else {
            var_dump($ret);
        }
        return null;
    }

    /**
     * 查询赛事赛程
     * 接口URL: http://data43.aistat.cn/competitions/fixture
     * 请求类型: get
     * 请求参数: key (必填, String), competitionId (必填, Int), season (必填, String), isFinish (可选, int)
     */
    public function getCompetitionsFixture() {
        $userKey = env('userKey');
        $competitionList = Competition::where('id', '<', 30)->get();
        foreach ($competitionList as $val) {
            //$ret = curlGetJson('http://data43.aistat.cn/competitions/fixture?key=ZQSJoL4D7uF9GBvKYHnJ&competitionId=' . $val['id'] . '&season=' .$val['currSeason']);
            //var_dump($val['id'],$ret['state']);
            $seasons = explode('|', $val['seasons']);
            foreach ($seasons as $value) {
                $season = str_replace('/', '-', $value);
                $arr = explode('-', $season);
                if (count($arr) == 2) {
                    if ($arr[1] < 21) {
                        continue;
                    }
                }
                if (count($arr) == 1) {
                    if ($arr[0] < 2021) {
                        continue;
                    }
                }
                $ret = curlGetJson('http://data43.aistat.cn/competitions/fixture?key=' . $userKey . '&competitionId=' . $val['id'] . '&season=' . $season);
                if ($ret['state'] == 'success') {
                    foreach ($ret['matchs'] as $data) {
                        \App\Models\Matchs::updateOrCreate(['id' => $data['id']], $data);
                    }
                } else {
                    var_dump($val['id'] . '|' . $season . '|' . $ret['errorMsg']);
                }
            }
        }

        return null;
    }

    /**
     * 根据日期查询赛事赛程
     * 接口URL: http://data43.aistat.cn/competitions/queryFixtureByDate
     * 请求类型: get
     * 请求参数: Key (必填, String), beginDate (必填, String), endDate (必填, String)
     */
    public function getCompetitionsFixtureByDate() {
        $userKey = env('userKey');
        $start_time = date('Ymd', strtotime('-1 days'));
        $end_time = date('Ymd', strtotime('+5 days'));
        $ret = curlGetJson('http://data43.aistat.cn/competitions/queryFixtureByDate?key=' . $userKey . '&beginDate=' . $start_time . '&endDate=' . $end_time);
        if ($ret['state'] == 'success') {
            foreach ($ret['matchs'] as $data) {
                \App\Models\Matchs::updateOrCreate(['id' => $data['id']], $data);
            }
        } else {
            var_dump($ret['errorMsg']);
        }
        return null;
    }

    /**
     * 查询赛程变更日志
     * 接口URL: http://data43.aistat.cn/matchs/modifyLogs
     * 请求类型: get
     * 请求参数: key (必填, String)
     */
    public function getMatchsModifyLogs() {
        $userKey = env('userKey');
        $ret = curlGetJson('http://data43.aistat.cn/matchs/modifyLogs?key=' . $userKey);
        if ($ret['state'] == 'success') {
            foreach ($ret['modifyLogs'] as $data) {
                \App\Models\Modifylog::updateOrCreate(['id' => $data['id']], $data);
            }
        } else {
            var_dump($ret['errorMsg']);
        }
        return null;
    }

    /**
     * 查询比赛预测首发阵容
     * 接口URL: http://data43.aistat.cn/matchs/previewStarters
     * 请求类型: get
     * 请求参数: key (必填, String), matchId (可选, String), matchIds (可选, String)
     */
    public function getMatchsPreviewStarters() {
        $userKey = env('userKey');
        $matchsList = Matchs::where('competitionId', '<', 30)->where('startTime', '>', date('Ymd'))->get();
        foreach ($matchsList as $value) {
            $ret = curlGetJson('http://data43.aistat.cn/matchs/previewStarters?key=' . $userKey . '&matchId=' . $value['id']);
            if ($ret['state'] == 'success') {
                foreach ($ret['matchs'] as $data) {
                    \App\Models\PreviewStarter::updateOrCreate(['id' => $data['id']], $data);
                }
            } else {
                var_dump($ret['errorMsg']);
            }
        }

        return null;
    }

    /**
     * 查询实时比分数据
     * 接口URL: http://data43.aistat.cn/matchs/liveScores
     * 请求类型: get
     * 请求参数: key (必填, String)
     */
    public function getMatchsLiveScores() {
        $userKey = env('userKey');
        $ret = curlGetJson('http://data43.aistat.cn/matchs/liveScores?key=' . $userKey);
        if ($ret['state'] == 'success') {
            foreach ($ret['liveScores'] as $data) {
                \App\Models\LiveScore::updateOrCreate(['id' => $data['id']], $data);
            }
        } else {
        }
        return null;
    }

    /**
     * 查询实时比赛进程
     * 接口URL: http://data43.aistat.cn/matchs/liveTimelines
     * 请求类型: get
     * 请求参数: key (必填, String), matchId (可选, String)
     */
    public function getMatchsLiveTimelines() {
        $userKey = env('userKey');
        $matchsList = Matchs::whereDate('startTime', Carbon::today())->get();
        foreach ($matchsList as $value) {
            $ret = curlGetJson('http://data43.aistat.cn/matchs/liveTimelines?key=' . $userKey . '&matchId=' . $value['id']);
            if ($ret['state'] == 'success') {
                foreach ($ret['matchs'] as $data) {
                    \App\Models\LiveTimeline::updateOrCreate(['id' => $data['id']], $data);
                }
            }
        }

        return null;
    }

    /**
     * 查询实时球员数据（简单）
     * 接口URL: http://data43.aistat.cn/matchs/liveSimplePlayerStats
     * 请求类型: get
     * 请求参数: key (必填, String), matchId (可选, String)
     */
    public function getMatchsLiveSimplePlayerStats() {
        $userKey = env('userKey');
        $matchsList = Matchs::whereDate('startTime', Carbon::today())->get();
        foreach ($matchsList as $value) {
            $ret = curlGetJson('http://data43.aistat.cn/matchs/liveSimplePlayerStats?key=' . $userKey . '&matchId=' . $value['id']);
            if ($ret['state'] == 'success') {
                foreach ($ret['matchs'] as $data) {
                    \App\Models\LivePlayer::updateOrCreate(['id' => $data['id']], $data);
                }
            }
        }

        return null;
    }

    /**
     * 查询实时球队数据（简单）
     * 接口URL: http://data43.aistat.cn/matchs/liveSimpleTeamStats
     * 请求类型: get
     * 请求参数: key (必填, String), matchId (可选, String)
     */
    public function getMatchsLiveSimpleTeamStats() {
        $userKey = env('userKey');
        $matchsList = Matchs::whereDate('startTime', Carbon::today())->get();
        foreach ($matchsList as $value) {
            $ret = curlGetJson('http://data43.aistat.cn/matchs/liveSimpleTeamStats?key=' . $userKey . '&matchId=' . $value['id']);
            if ($ret['state'] == 'success') {
                foreach ($ret['matchs'] as $data) {
                    \App\Models\LiveTeam::updateOrCreate(['id' => $data['id']], $data);
                }
            }
        }

        return null;
    }

    /**
     * 查询实时比赛形势
     * 接口URL: http://data43.aistat.cn/matchs/liveTrend
     * 请求类型: get
     * 请求参数: key (必填, String), matchId (可选, String)
     */
    public function getMatchsLiveTrend() {
        $userKey = env('userKey');
        $matchsList = Matchs::whereDate('startTime', Carbon::today())->get();
        foreach ($matchsList as $value) {
            $ret = curlGetJson('http://data43.aistat.cn/matchs/liveTrend?key=' . $userKey . '&matchId=' . $value['id']);
            if ($ret['state'] == 'success') {
                foreach ($ret['matchs'] as $data) {
                    \App\Models\LiveTrend::updateOrCreate(['id' => $data['id']], $data);
                }
            }
        }
        return null;
    }

    /**
     * 查询实时竞彩足球赔率
     * 接口URL: http://data36.aistat.cn/lotteries/jczqOdds
     * 请求类型: get
     * 请求参数: key (必填, String), issueNum (可选, String)
     */
    public function getLotteriesJczqOdds() {
        $userKey = env('userKey');
        $ret = curlGetJson('http://data36.aistat.cn/lotteries/jczqOdds?key=' . $userKey);
        if ($ret['state'] == 'success') {
            foreach ($ret['jczqOdds'] as $data) {
                \App\Models\JczqOdd::updateOrCreate(['id' => $data['id']], $data);
            }
        }
        return null;
    }

    /**
     * 查询实时北京单场SP值
     * 接口URL: http://data36.aistat.cn/lotteries/bjdcOdds
     * 请求类型: get
     * 请求参数: key (必填, String), issueNum (可选, String)
     */
    public function getLotteriesBjdcOdds() {
        $userKey = env('userKey');
        $ret = curlGetJson('http://data36.aistat.cn/lotteries/bjdcOdds?key=' . $userKey);
        if ($ret['state'] == 'success') {
            foreach ($ret['bjdcOdds'] as $data) {
                \App\Models\BjdcOdd::updateOrCreate(['id' => $data['id']], $data);
            }
        }
        return null;
    }

    /**
     * 查询实时北单胜负过关玩法SP值
     * 接口URL: http://data36.aistat.cn/lotteries/bjdcSfggOdds
     * 请求类型: get
     * 请求参数: key (必填, String), issueNum (可选, String)
     */
    public function getLotteriesBjdcSfggOdds() {
        $userKey = env('userKey');
        $ret = curlGetJson('http://data36.aistat.cn/lotteries/bjdcSfggOdds?key=' . $userKey);
        if ($ret['state'] == 'success') {
            foreach ($ret['bjdcSfggOdds'] as $data) {
                \App\Models\BjdcsfOdd::updateOrCreate(['id' => $data['id']], $data);
            }
        }
        return null;
    }

    /**
     * 查询竞彩足球开奖结果（最近24小时/指定查询条件）
     * 接口URL: http://data36.aistat.cn/lotteries/jczqResults
     * 请求类型: get
     * 请求参数: key (必填, String), issueNum (可选, String)
     */
    public function getLotteriesJczqResults() {
        $userKey = env('userKey');
        // TODO: Implement logic for getLotteriesJczqResults
        return null;
    }

    /**
     * 查询北京单场开奖结果（最近24小时/指定查询条件）
     * 接口URL: http://data36.aistat.cn/lotteries/bjdcResults
     * 请求类型: get
     * 请求参数: key (必填, String), issueNum (可选, String)
     */
    public function getLotteriesBjdcResults() {
        $userKey = env('userKey');
        // TODO: Implement logic for getLotteriesBjdcResults
        return null;
    }

    /**
     * 查询北京单场胜负过关开奖结果（最近24小时/指定查询条件）
     * 接口URL: http://data36.aistat.cn/lotteries/bjdcSfggResults
     * 请求类型: get
     * 请求参数: key (必填, String), issueNum (可选, String)
     */
    public function getLotteriesBjdcSfggResults() {
        $userKey = env('userKey');
        // TODO: Implement logic for getLotteriesBjdcSfggResults
        return null;
    }

    /**
     * 查询传统足彩赛程和开奖信息
     * 接口URL: http://data36.aistat.cn/lotteries/ctzc
     * 请求类型: get
     * 请求参数: key (必填, String), issueNum (可选, String)
     */
    public function getLotteriesCtzc() {
        $userKey = env('userKey');
        // TODO: Implement logic for getLotteriesCtzc
        return null;
    }

    /**
     * 查询指数公司基本信息
     * 接口URL: http://data61.aistat.cn/companies/infos
     * 请求类型: get
     * 请求参数: key (必填, String)
     */
    public function getCompaniesInfos() {
        $userKey = env('userKey');
        $ret = curlGetJson('http://data61.aistat.cn/companies/infos?key=' . $userKey);
        if ($ret['state'] == 'success') {
            foreach ($ret['companies'] as $data) {
                \App\Models\Companie::updateOrCreate(['id' => $data['id']], $data);
            }
        }
        return null;
    }

    /**
     * 查询赛前盘指数（全量）
     * 接口URL: http://data61.aistat.cn/zhishu/v1/mainOdds
     * 请求类型: get
     * 请求参数: key (必填, String), date (必填, String)
     */
    public function getZhishuMainOdds() {
        $userKey = env('userKey');
        $ret = curlGetJson('http://data61.aistat.cn/zhishu/v1/mainOdds?key=' . $userKey . '&date=more');
        if ($ret['state'] == 'success') {
            foreach ($ret['mainOdds'] as $data) {
                \App\Models\MainOdd::updateOrCreate(['id' => $data['id']], $data);
            }
        }
        return null;
    }

    /**
     * 查询赛前盘指数（30秒内变盘）
     * 接口URL: http://data61.aistat.cn/zhishu/v1/mainOddsChange
     * 请求类型: get
     * 请求参数: key (必填, String)
     */
    public function getZhishuMainOddsChange() {
        $userKey = env('userKey');
        // TODO: Implement logic for getZhishuMainOddsChange
        return null;
    }

    /**
     * 查询其它类型赔率
     * 接口URL: http://data61.aistat.cn/zhishu/v1/otherOdds
     * 请求类型: get
     * 请求参数: key (必填, String), date (必填, String), type (必填, String)
     */
    public function getZhishuOtherOdds() {
        $userKey = env('userKey');
        $ret = curlGetJson('http://data61.aistat.cn/zhishu/v1/otherOdds?key=' . $userKey . '&date=more');
        if ($ret['state'] == 'success') {
            foreach ($ret['otherOdds'] as $data) {
                \App\Models\OtherOdd::updateOrCreate(['id' => $data['id']], $data);
            }
        }
        var_dump($ret);
        return null;
    }

    /**
     * 查询其它类型赔率（30秒内变盘）
     * 接口URL: http://data61.aistat.cn/zhishu/v1/otherOddsChange
     * 请求类型: get
     * 请求参数: key (必填, String), type (必填, String)
     */
    public function getZhishuOtherOddsChange() {
        $userKey = env('userKey');
        // TODO: Implement logic for getZhishuOtherOddsChange
        return null;
    }

    /**
     * 查询球员赛季数据
     * 接口URL: http://data43.aistat.cn/players/stats
     * 请求类型: get
     * 请求参数: key (必填, String), playerId (可选, Int), teamId (可选, Int), isCurSeason (必填, Int)
     */
    public function getPlayersStats() {
        $userKey = env('userKey');
        $ret = curlGetJson('http://data43.aistat.cn/players/stats?key=' . $userKey . '&playerId=25&teamId=13&isCurSeason=0');
        if ($ret['state'] == 'success') {
            foreach ($ret['matchs'] as $data) {
                \App\Models\PlayerStats::updateOrCreate(['id' => $data['id']], $data);
            }
        }
        return null;
    }

    /**
     * 根据赛事查询球员赛季数据
     * 接口URL: http://data43.aistat.cn/players/getStatsByCompetition
     * 请求类型: get
     * 请求参数: key (必填, String), competitionId (必填, Int), season (必填, String)
     */
    public function getPlayersStatsByCompetition() {
        $userKey = env('userKey');
        // TODO: Implement logic for getPlayersStatsByCompetition
        return null;
    }

    /**
     * 查询球队赛季数据
     * 接口URL: http://data43.aistat.cn/teams/stats
     * 请求类型: get
     * 请求参数: key (必填, String), teamId (必填, Int), isCurSeason (必填, Int)
     */
    public function getTeamsStats() {
        $userKey = env('userKey');
        // TODO: Implement logic for getTeamsStats
        return null;
    }

    /**
     * 根据赛事查询球队赛季数据
     * 接口URL: http://data43.aistat.cn/teams/getStatsByCompetition
     * 请求类型: get
     * 请求参数: key (必填, String), competitionId (必填, Int), season (必填, String)
     */
    public function getTeamsStatsByCompetition() {
        $userKey = env('userKey');
        // TODO: Implement logic for getTeamsStatsByCompetition
        return null;
    }

    /**
     * 查询历史主盘口指数
     * 接口URL: http://data61.aistat.cn/zhishu/v1/mainOddsHistory
     * 请求类型: get
     * 请求参数: key (必填, String), date (可选, String), matchIds (可选, String)
     */
    public function getZhishuMainOddsHistory() {
        $userKey = env('userKey');
        // TODO: Implement logic for getZhishuMainOddsHistory
        return null;
    }
}
